package pct.search;

import java.util.LinkedList;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import pct.database.PcServiceImpl;
import pct.entity.Group;
import pct.entity.Post;
import pct.entity.Topic;
import pct.entity.User;
import pct.manage.StatusManager;
import pct.page.PageFilter;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings("serial")
public class Search extends ActionSupport implements Preparable, SessionAware {
	private String target;
	private String searchType;
	private PcServiceImpl pcService = new PcServiceImpl();
	private Map<String, Object> session;

	public String execute() {
		StatusManager sm = (StatusManager) session.get("status");
		if(sm == null) {
			sm = new StatusManager();
			User visitor = new User();
			visitor.setUsername("visitor");
			sm.setCurrentUser(visitor);
			session.put("status", sm);
		}
		if(searchType.equals("group")) {
			sm.setPageType(4);
			PageFilter pf = new PageFilter();
			LinkedList<Group> ret = pf.getFirstPageMatchedGroups(target);
			sm.setCurrentPage(1);
			if (ret != null) {
				for (Group i : ret) {
					i.setTopicNumber(pcService.retrieveTopicNumber(i
							.getGroupName()));
					i.setPostNumber(pcService.retrievePostNumber(i
							.getGroupName()));
				}
			}
			sm.setSearchedGroups(ret);
			session.put("status", sm);
		} else if (searchType.equals("topic")){
			sm.setPageType(5);
			PageFilter pf = new PageFilter();
			LinkedList<Topic> ret = pf.getFirstPageMatchedTopics(target);
			sm.setCurrentPage(1);
			sm.setSearchedTopics(ret);
			session.put("status", sm);
		} else if(searchType.equals("post")) {
			sm.setPageType(6);
			PageFilter pf = new PageFilter();
			LinkedList<Post> ret = pf.getFirstPageMatchedPosts(target);
			sm.setCurrentPage(1);
			if (ret != null) {
				for (Post i : ret) {
					i.setUserID(i.getUserID());
					i.setPostTime(i.getPostTime());
					i.setGroupName(pcService.retrieveGroupName(i.getTopicID()));
					i.setTitle(pcService.retrieveTitle(i.getTopicID()));
				}
			}
			sm.setSearchedPosts(ret);
			session.put("status", sm);
		}
		return SUCCESS;
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}

	@Override
	public void prepare() throws Exception {
		pcService.connectDB();
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}
